package cn.xxy.converter;

import cn.xxy.TypeConverter;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @author xxy
 * @date 2024/11/20
 */
public class BaseTypeConverter implements TypeConverter {

    @Override
    public boolean supports(Class<?> fieldType) {
        String targetType = fieldType.getName();
        return switch (targetType) {
            case "java.lang.byte", "java.lang.boolean","java.lang.short", "java.lang.int", "java.lang.long", "java.lang.float", "java.lang.double"
             ,"java.lang.Byte","java.lang.Boolean","java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double"
             ,"java.math.BigDecimal", "java.lang.char","java.lang.Character" ,"java.lang.String" -> true;
            default -> false;
        };
    }

    @Override
    public Object apply(Class<?> fieldType, Object value) {
        if(value==null || fieldType.equals(value.getClass())) {
            return value;
        }
        String targetType = fieldType.getName();
        return switch (targetType) {
            case "java.lang.byte" -> Byte.parseByte(value.toString()) ;
            case "java.lang.Byte" -> Byte.parseByte(value.toString()) ;
            case "java.lang.short" -> Short.parseShort(value.toString()) ;
            case "java.lang.Short" -> Short.parseShort(value.toString()) ;
            case "java.lang.int" -> Integer.parseInt(value.toString()) ;
            case "java.lang.Integer" -> Integer.parseInt(value.toString()) ;
            case "java.lang.long" -> Long.parseLong(value.toString()) ;
            case "java.lang.Long" -> Long.parseLong(value.toString()) ;
            case "java.lang.float" -> Float.parseFloat(value.toString()) ;
            case "java.lang.Float" -> Float.parseFloat(value.toString()) ;
            case "java.lang.double" -> Double.parseDouble(value.toString()) ;
            case "java.lang.Double" -> Double.parseDouble(value.toString()) ;
            case "java.lang.boolean" -> Boolean.parseBoolean(value.toString()) ;
            case "java.lang.Boolean" -> Boolean.parseBoolean(value.toString()) ;
            case "java.lang.char" -> value.toString().charAt(0) ;
            case "java.lang.Character" -> value.toString().charAt(0) ;
            case "java.lang.String" -> value.toString() ;
            case "java.math.BigInteger" -> new BigInteger(value.toString()) ;
            case "java.math.BigDecimal" -> new BigDecimal(value.toString()) ;
            //case byte.class -> Byte.parseByte(value.toString()) ;
            default -> value;
        };
    }

}
